package com.cr.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.cr.model.OrderDetail;
import com.cr.util.DBUtil;

/**
 * @author Administrator
 *
 */
public class OrderDetailDao {
	private DBUtil db=new DBUtil();
	
	/**
	 * @param id
	 * @return
	 */
	public OrderDetail getOrderDetail(long id)
	{
		OrderDetail orderDetail=null;
		
		String sql="select * from orderdetail where Id=?";
		Object[] args={id};
		ResultSet rs=db.preQuery(sql, args);
		
		if(rs!=null)
		{
			try {
				if(rs.next())
				{
					orderDetail=new OrderDetail();
					
					orderDetail.setClothId(rs.getLong("ClothId"));
					orderDetail.setId(id);
					orderDetail.setOrderId(rs.getLong("OrderId"));
					orderDetail.setQuantity(rs.getInt("Quantity"));
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return orderDetail;
	}
	/**
	 * @param orderDetail
	 * @return
	 */
	public boolean addOrderDetail(OrderDetail orderDetail)
	{
		boolean flag=false;
		String sql="insert into orderdetail(ClothId,OrderId,Quantity) ";
		sql+=" values(?,?,?)";
		
		Object[] args={orderDetail.getClothId(),
				orderDetail.getOrderId(),
				orderDetail.getQuantity()};
		
		int count=db.preExecute(sql, args);
		
		flag=count>0;
		
		return flag;
	}
	/**
	 * @param orderDetail
	 * @return
	 */
	public boolean updateOrderDetail(OrderDetail orderDetail)
	{
		boolean flag=false;
		String sql="update orderdetail set ";
		sql+=" ClothId=?,";
		sql+=" OrderId=?,";
		sql+=" Quantity=?";
		sql+=" where Id=?";
		
		Object[] args={orderDetail.getClothId(),
				orderDetail.getOrderId(),
				orderDetail.getQuantity(),
				orderDetail.getId()};
		
		int count=db.preExecute(sql, args);
		
		flag=count>0;
		
		return flag;
	}
	/**
	 * @param id
	 * @return
	 */
	public boolean deleteOrderDetail(long id)
	{
		boolean flag=false;
		String sql="delete from orderdetail where Id=?";
		
		Object[] args={id};
		
		int count=db.preExecute(sql, args);
		
		flag=count>0;
		
		return flag;
	}
	
	/**
	 * @param id
	 * @return
	 */
	public List<OrderDetail> getOrderDetails(long id)
	{
		List<OrderDetail> list=null;
		
		String sql="select * from orderdetail where OrderId=?";
		Object[] args={id};
		
		ResultSet rs=db.preQuery(sql, args);
		
		if(rs!=null)
		{
			list=new ArrayList<OrderDetail>();
			try {
				while(rs.next())
				{
					OrderDetail detail=new OrderDetail();
					
					detail.setClothId(rs.getLong("ClothId"));
					detail.setId(rs.getLong("Id"));
					detail.setOrderId(rs.getLong("OrderId"));
					detail.setQuantity(rs.getInt("Quantity"));
					
					list.add(detail);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return list;
	}
}
